package com.manage.platform.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.manage.platform.context.UserContext;
import com.manage.platform.dto.*;
import com.manage.platform.dto.query.TaskPageQuery;
import com.manage.platform.entity.*;
import com.manage.platform.exception.CommonException;
import com.manage.platform.mapper.TaskMapper;
import com.manage.platform.utils.RPage;
import com.manage.platform.utils.TreeListTaskTreeOneUtil;
import com.manage.platform.utils.TreeListTaskTreeUtil;
import com.manage.platform.vo.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * YWD
 * 2025/9/23
 */
@Slf4j
@AllArgsConstructor
@Service
public class TaskServiceImpl extends ServiceImpl<TaskMapper, TaskEntity> {

    private final TaskFileServiceImpl taskFileServiceImpl;
    private final TaskParticipantServiceImpl taskParticipantServiceImpl;
    private final TaskTargetServiceImpl taskTargetServiceImpl;
    private final TaskTargetFileServiceImpl taskTargetFileServiceImpl;
    private final TaskOperationLogServiceImpl taskOperationLogServiceImpl;
    private final TaskBudgetServiceImpl taskBudgetServiceImpl;
    private final TaskFinalAccountServiceImpl taskFinalAccountServiceImpl;
    private final TaskAchieveServiceImpl taskAchieveServiceImpl;

    private final TreeListTaskTreeOneUtil treeListTaskTreeOneUtil;



    public RPage<List<TaskPartVo>> getTaskPage(TaskPageQuery query) {
        UserVo userVo = UserContext.getUser();
        if (query.getType().equals("SELF")) {
            query.setUserId(userVo.getId());
        }
        Page<Object> page = PageHelper.startPage(query.getPage(), query.getLimit());
        List<TaskPartVo> list = this.baseMapper.getTaskPage(query);
        return RPage.ok(list, query.getPage(), query.getLimit(), page.getTotal());
    }

    public TaskDetailsVo getTaskDetails(Long id) {
        return this.baseMapper.getTaskDetails(id);
    }

//    @Transactional(rollbackFor = Exception.class)
//    public Boolean saveTask(TaskDto dto) {
//        UserVo userVo = UserContext.getUser();
//        dto.setUserId(userVo.getId());
//        //个人或学院任务
//        try {
//            //1.新增任务
//            this.baseMapper.saveTask(dto);
//            //2.新增任务附件
//            List<String> fileList = dto.getFileList();
//            if (CollectionUtil.isNotEmpty(fileList)) {
//                List<TaskFileEntity> list = fileList.stream().map(it -> {
//                    TaskFileEntity taskFileEntity = new TaskFileEntity();
//                    taskFileEntity.setTaskId(dto.getId());
//                    taskFileEntity.setFileUrl(it);
//                    return taskFileEntity;
//                }).toList();
//                taskFileServiceImpl.saveBatch(list);
//            }
//            //3.任务参与者
//            List<Long> participantList = dto.getParticipantList();
//            if (CollectionUtil.isNotEmpty(participantList)) {
//                List<TaskParticipantEntity> list = participantList.stream().map(it -> {
//                    TaskParticipantEntity taskParticipantEntity = new TaskParticipantEntity();
//                    taskParticipantEntity.setTaskId(dto.getId());
//                    taskParticipantEntity.setParticipantId(it);
//                    return taskParticipantEntity;
//                }).toList();
//                taskParticipantServiceImpl.saveBatch(list);
//            }
//            //4.任务目标值
//            List<TaskTargetDto> targetDtoList = dto.getTargetDtoList();
//            if (CollectionUtil.isNotEmpty(targetDtoList)) {
//                targetDtoList.forEach(it -> {
//                    it.setTaskId(dto.getId());
//                    TaskTargetDto taskTargetDto = taskTargetServiceImpl.saveTaskTarget(it);
//                    //任务目标值附件
//                    List<String> fileList1 = it.getFileList();
//                    if (CollectionUtil.isNotEmpty(fileList1)) {
//                        List<TaskTargetFileEntity> list = fileList1.stream().map(file -> {
//                            TaskTargetFileEntity taskTargetFileEntity = new TaskTargetFileEntity();
//                            taskTargetFileEntity.setTaskTargetId(taskTargetDto.getId());
//                            taskTargetFileEntity.setFileUrl(file);
//                            return taskTargetFileEntity;
//                        }).toList();
//                        taskTargetFileServiceImpl.saveBatch(list);
//                    }
//                });
//            }
//            //5.动态&评论
//            TaskOperationLogDto taskOperationLogDto = new TaskOperationLogDto();
//            taskOperationLogDto
//                    .setTaskId(dto.getId())
//                    .setUserId(userVo.getId())
//                    .setRealName(userVo.getRealName())
//                    .setDescription("创建任务");
//            return taskOperationLogServiceImpl.save(BeanUtil.copyProperties(taskOperationLogDto, TaskOperationLogEntity.class));
//        } catch (Exception e) {
//            log.error(e.getMessage(), e);
//            throw new CommonException("创建任务失败");
//        }
//    }
//
//    @Transactional(rollbackFor = Exception.class)
//    public Boolean updateTask(TaskUpdateDto dto) {
//        UserVo userVo = UserContext.getUser();
//        dto.setUserId(userVo.getId());
//        try {
//            //1.修改任务
//            this.baseMapper.updateById(BeanUtil.copyProperties(dto, TaskEntity.class));
//            //2.删除再新增新增任务附件
//            taskFileServiceImpl.removeByTaskId(dto.getId());
//            List<String> fileList = dto.getFileList();
//            if (CollectionUtil.isNotEmpty(fileList)) {
//                List<TaskFileEntity> list = fileList.stream().map(it -> {
//                    TaskFileEntity taskFileEntity = new TaskFileEntity();
//                    taskFileEntity.setTaskId(dto.getId());
//                    taskFileEntity.setFileUrl(it);
//                    return taskFileEntity;
//                }).toList();
//                taskFileServiceImpl.saveBatch(list);
//            }
//            //3.删除再新增任务参与者
//            taskParticipantServiceImpl.removeByTaskId(dto.getId());
//            List<CommonVo> participantList = dto.getParticipantList();
//            if (CollectionUtil.isNotEmpty(participantList)) {
//                List<TaskParticipantEntity> list = participantList.stream().map(it -> {
//                    TaskParticipantEntity taskParticipantEntity = new TaskParticipantEntity();
//                    taskParticipantEntity.setTaskId(dto.getId());
//                    taskParticipantEntity.setParticipantId(it.getId());
//                    return taskParticipantEntity;
//                }).toList();
//                taskParticipantServiceImpl.saveBatch(list);
//            }
//            //4.删除再新增任务目标值
//            taskTargetServiceImpl.removeByTaskId(dto.getId());
//            List<TaskTargetDto> targetDtoList = dto.getTargetDtoList();
//            if (CollectionUtil.isNotEmpty(targetDtoList)) {
//                targetDtoList.stream().forEach(it -> {
//                    it.setTaskId(dto.getId());
//                    TaskTargetDto taskTargetDto = taskTargetServiceImpl.saveTaskTarget(it);
//                    //新增任务目标值附件
//                    List<String> fileList1 = it.getFileList();
//                    if (CollectionUtil.isNotEmpty(fileList1)) {
//                        List<TaskTargetFileEntity> list = fileList1.stream().map(file -> {
//                            TaskTargetFileEntity taskTargetFileEntity = new TaskTargetFileEntity();
//                            taskTargetFileEntity.setTaskTargetId(taskTargetDto.getId());
//                            taskTargetFileEntity.setFileUrl(file);
//                            return taskTargetFileEntity;
//                        }).toList();
//                        taskTargetFileServiceImpl.saveBatch(list);
//                    }
//                });
//            }
//            //5.动态&评论
//            TaskOperationLogDto taskOperationLogDto = new TaskOperationLogDto();
//            taskOperationLogDto
//                    .setTaskId(dto.getId())
//                    .setUserId(userVo.getId())
//                    .setRealName(userVo.getRealName())
//                    .setDescription("修改任务");
//            return taskOperationLogServiceImpl.save(BeanUtil.copyProperties(taskOperationLogDto, TaskOperationLogEntity.class));
//        } catch (Exception e) {
//            log.error(e.getMessage(), e);
//            throw new CommonException("修改任务失败");
//        }
//    }

    public Boolean deleteTask(Long id) {
        //任务附件、任务参与者、任务目标值、动态&评论（关联数据暂不删除）
        return removeById(id);
    }

    public Boolean deleteTaskBatch(List<Long> ids) {
        //任务附件、任务参与者、任务目标值、动态&评论（关联数据暂不删除）
        return removeByIds(ids);
    }

    public List<CommonVo> getTaskList(String name) {
        return this.baseMapper.getTaskList(name);
    }


    public List<CommonVo> getTaskListOne(String name) {
        return this.baseMapper.getTaskListOne(name);
    }

    //任务列表=======================================================================================================
    //=============================================================================================================
    public TaskStatisticsVo statistics(Long organizeId) {
        return this.baseMapper.statistics(organizeId);
    }


    public List<CommonVo> getAnnualList() {
        List<CommonVo> list = new ArrayList<>();
        // 添加"全部"选项
        CommonVo allOption = new CommonVo();
        allOption.setId(-1L);
        allOption.setName("全部年度");
        list.add(allOption);
        List<String> list1 = this.baseMapper.getAnnualList();
        for (int i = 0; i < list1.size(); i++) {
            CommonVo collegeVo = new CommonVo();
            collegeVo.setId((long) i + 2025); // 生成ID，从1开始
            collegeVo.setName(list1.get(i) + "年");
            list.add(collegeVo);
        }
        return list;
    }

    public List<TaskTreePartVo> taskListTreePart(Long organizeId, String annual,Boolean isAdd) {
        List<TaskTreePartVo> list = this.baseMapper.taskListTreePart(organizeId, annual);
        if (CollectionUtil.isEmpty(list)) return null;
        if (isAdd) {
            return treeListTaskTreeOneUtil.buildMenuTreeList(list);
        }
        return TreeListTaskTreeUtil.buildMenuTreeList(list);
    }

    public List<TaskTreePartOneVo> taskListTreePartOne(Long organizeId) {
        List<TaskTreePartOneVo> list = this.baseMapper.taskListTreePartOne(organizeId);
        if (CollectionUtil.isEmpty(list)) return null;
        return TreeListTaskTreeUtil.buildMenuTreeListOne(list);
    }

    public Boolean updateListTreePartOne(TaskPartUpdateDto dto) {
        return updateById(BeanUtil.copyProperties(dto, TaskEntity.class));
    }

    public Boolean addListTreePartOne(TaskPartAddDto dto) {
        if (ObjectUtil.isEmpty(dto.getParentId())) throw new CommonException("父任务ID必传");
        UserVo userVo = UserContext.getUser();
        dto.setUserId(userVo.getId());
        //判断当前层级
        TaskEntity parent = getById(dto.getParentId());
        dto.setLevel(parent.getLevel() + 1);
        Integer i = Integer.valueOf(parent.getAnnual());
        i += 1;
        dto.setAnnual(i.toString());
        dto.setStatus(parent.getStatus());
        return save(BeanUtil.copyProperties(dto, TaskEntity.class));
    }

    public TaskBudgetAndFinalAccountVo getTaskBudget(Long id) {
        TaskBudgetAndFinalAccountVo vo = new TaskBudgetAndFinalAccountVo();
        TaskBudgetVo taskBudget = taskBudgetServiceImpl.getByTaskId(id);
        if (ObjectUtil.isNotEmpty(taskBudget)) {
            vo.setTaskBudget(taskBudget);
        }
        TaskFinalAccountVo finalAccount = taskFinalAccountServiceImpl.getByTaskId(id);
        if (ObjectUtil.isNotEmpty(taskBudget)) {
            vo.setFinalAccount(finalAccount);
        }
        return vo;
    }


    public Boolean addFinalAccount(TaskFinalAccountDto dto) {
        UserVo userVo = UserContext.getUser();
        dto.setUserId(userVo.getId());
        //记录操作
        TaskOperationLogDto taskOperationLogDto = new TaskOperationLogDto();
        taskOperationLogDto
                .setTaskId(dto.getTaskId())
                .setUserId(userVo.getId())
                .setRealName(userVo.getRealName())
                .setDescription("上传任务决算信息");
        taskOperationLogServiceImpl.save(BeanUtil.copyProperties(taskOperationLogDto, TaskOperationLogEntity.class));

        TaskEntity taskEntity = this.getById(dto.getTaskId());
        dto.setAnnual(taskEntity.getAnnual());

        return taskFinalAccountServiceImpl.addFinalAccount(dto);
    }


    public Boolean updateFinalAccount(TaskFinalAccountDto dto) {
        UserVo userVo = UserContext.getUser();
        //记录操作
        TaskOperationLogDto taskOperationLogDto = new TaskOperationLogDto();
        taskOperationLogDto
                .setTaskId(dto.getId())
                .setUserId(userVo.getId())
                .setRealName(userVo.getRealName())
                .setDescription("修改任务决算信息");
        taskOperationLogServiceImpl.save(BeanUtil.copyProperties(taskOperationLogDto, TaskOperationLogEntity.class));
        return taskFinalAccountServiceImpl.updateFinalAccount(dto);
    }


    public List<CommonVo> getTaskAchieveList(Long id) {
        return taskAchieveServiceImpl.getByTaskId(id);
    }


    public TaskAchieveDetailsVo getTaskAchieveDetails(Long taskAchieveId) {
        return taskAchieveServiceImpl.getTaskAchieveDetails(taskAchieveId);
    }


    public Boolean saveTaskAchieve(TaskAchieveDetailsDto dto) {
        //记录操作
        UserVo userVo = UserContext.getUser();
        dto.setUserId(userVo.getId());
        //记录操作
        TaskOperationLogDto taskOperationLogDto = new TaskOperationLogDto();
        taskOperationLogDto
                .setTaskId(dto.getTaskId())
                .setUserId(userVo.getId())
                .setRealName(userVo.getRealName())
                .setDescription("添加任务成果");
        taskOperationLogServiceImpl.save(BeanUtil.copyProperties(taskOperationLogDto, TaskOperationLogEntity.class));
        return taskAchieveServiceImpl.saveTaskAchieve(dto);
    }


    public Boolean updateTaskAchieve(TaskAchieveDetailsDto dto) {
        //记录操作
        UserVo userVo = UserContext.getUser();
        dto.setUserId(userVo.getId());
        //记录操作
        TaskOperationLogDto taskOperationLogDto = new TaskOperationLogDto();
        taskOperationLogDto
                .setTaskId(dto.getTaskId())
                .setUserId(userVo.getId())
                .setRealName(userVo.getRealName())
                .setDescription("修改任务成果");
        taskOperationLogServiceImpl.save(BeanUtil.copyProperties(taskOperationLogDto, TaskOperationLogEntity.class));

        return taskAchieveServiceImpl.updateTaskAchieve(dto);
    }


    public Boolean deleteTaskAchieve(Long taskAchieveId) {
        UserVo userVo = UserContext.getUser();
        TaskAchieveEntity entity = taskAchieveServiceImpl.getById(taskAchieveId);
        //记录操作
        TaskOperationLogDto taskOperationLogDto = new TaskOperationLogDto();
        taskOperationLogDto
                .setTaskId(entity.getTaskId())
                .setUserId(userVo.getId())
                .setRealName(userVo.getRealName())
                .setDescription("删除任务成果");
        return taskAchieveServiceImpl.deleteTaskAchieve(taskAchieveId);
    }


}
